import { wsURL } from "@/api/config";
import {
  LocalTrack,
  RemoteTrack,
  Room,
  RoomEvent,
  Track,
  createLocalTracks
} from "livekit-client";

export const useLiveKit = (
  subscribeCallback: () => void,
  disconnectedCallBack: () => void
) => {
  const room: Room = new Room();
  // 加入房间
  const join = async (token: string) => {
    await room.connect(wsURL, token);
  };
  // 创建流
  let localAudioTrack: LocalTrack<Track.Kind>;
  let localVideoTrack: LocalTrack<Track.Kind>;
  const createTrack = async () => {
    // 创建本地轨道，但不立即发布
    const tracks = await createLocalTracks({
      audio: true,
      video: true
    });
    localAudioTrack = tracks.find(track => track.kind === "audio");
    localVideoTrack = tracks.find(track => track.kind === "video");
    localVideoTrack.attach(document.querySelector("#local"));
  };
  // 发布流
  const publish = async () => {
    if (!room || !localAudioTrack || !localVideoTrack) return;
    await room.localParticipant.publishTrack(localAudioTrack);
    await room.localParticipant.publishTrack(localVideoTrack);
  };
  // 离开房间
  const leaveRoom = async () => {
    await room.disconnect();
    // 取消本地流
    localAudioTrack.detach(document.querySelector("#local"));
    localVideoTrack.detach(document.querySelector("#local"));
  };
  // 事件处理，接收流
  room.on(RoomEvent.TrackSubscribed, (track: RemoteTrack) => {
    if (track.kind === "video" || track.kind === "audio") {
      track.attach(document.querySelector("#remote"));
      subscribeCallback();
    }
  });
  // 事件处理，对方离开
  room.on(RoomEvent.ParticipantDisconnected, () => {
    leaveRoom();
    disconnectedCallBack();
  });
  return {
    room,
    createTrack,
    publish,
    leaveRoom,
    join
  };
};
